package com.sysd.context;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.sysd.entity.LoginUser;
import com.sysd.exception.ServiceException;

/**
 * @description:
 * @author: bsh
 * @date: 2025/5/30 11:26
 */
public class UserContext {
    private static final ThreadLocal<LoginUser> LOGIN_USER = new TransmittableThreadLocal<>();

    /**
     * 设置用户
     *
     * @param loginUser 当前登入的用户
     */
    public static void setUser(LoginUser loginUser) {
        LOGIN_USER.set(loginUser);
    }

    /**
     * 获取用户信息
     *
     * @return LoginUser 当前登入的用户信息
     */
    public static LoginUser getLoginUser() {
        LoginUser loginUser = LOGIN_USER.get();
        if(null == loginUser || null == loginUser.getUserId()||0>=loginUser.getUserId()) {
            throw new ServiceException("获取用户信息失败!");
        }
        return LOGIN_USER.get();
    }

    /**
     * 删除当前缓存的用户信息
     */
    public static void clear() {
        LOGIN_USER.remove();
    }
}
